<script>
import { defineComponent, computed } from 'vue';
import { createNamespace, transformSize, transformStyleSize } from '../utils';

export default defineComponent({
  name: createNamespace('Icon')[0],
  options: {
    // https://uniapp.dcloud.io/matter.html#mp
    virtualHost: true,
  },
  emits: ['click'],
  props: {
    customStyle: [String, Object],
    /**
     * 图标名称或图片链接
     */
    name: String,
    size: {
      type: [String, Number],
      default: 'inherit',
    },
    // css 属性
    verticalAlign: String,
    /**
     * 图标颜色：red，支持渐变：linear-gradient(to right, red, blue)
     */
    color: {
      type: String,
      default: 'inherit',
    },
  },
  setup(props, context) {
    const imgIcon = computed(() => props.name?.includes('/'));
    const theStyle = computed(() => {
      let { name, color, size, verticalAlign, customStyle } = props;
      const fsize = transformSize(size === 'inherit' ? '14px' : size);
      let str = '';
      if (verticalAlign) {
        str += `--fan-icon-align-v:${verticalAlign};`;
      }
      if (imgIcon.value) {
        name = name.replace(/\"/g, "'");
        str += `width:${fsize};height:${fsize};`;
        if (color && color !== 'inherit') {
          str +=
            '-webkit-mask-image:url("' +
            `${name}` +
            '");mask-image:url("' +
            `${name}` +
            '");-webkit-mask-size:cover;mask-size:cover;background:' +
            `${color}`;
        } else {
          str +=
            'background:url("' + `${name}` + '") center / cover no-repeat;';
        }
      } else {
        str += `font-size:${fsize};`;
        if (color?.includes('-gradient')) {
          str += `color:transparent;background-image:${color};`;
        } else {
          str += `color:${color};`;
        }
      }
      return transformStyleSize(customStyle) + str;
    });

    const onClick = (e) => {
      context.emit('click', e);
    };

    return { imgIcon, theStyle, onClick };
  },
});
</script>

<template>
  <div
    v-if="imgIcon"
    :style="theStyle"
    class="fan-icon--img"
    @click="onClick"
  ></div>
  <div
    v-else
    :style="theStyle"
    :class="['fan-icon', 'icon-' + name]"
    @click="onClick"
  ></div>
</template>

<style lang="less">
@import './font/iconfont.css';

.fan-icon,
.fan-icon--img {
  display: inline-block;
  line-height: 1;
  vertical-align: var(--fan-icon-align-v);
}

.fan-icon {
  text-rendering: auto;
  background-clip: text;
  -webkit-background-clip: text;

  &::before {
    display: inline-block;
    vertical-align: var(--fan-icon-align-v);
  }
}

.fan-icon--img {
  mask-repeat: no-repeat;
}
</style>
